<script setup>
import { Plus } from '@element-plus/icons-vue'
//声明属性

const props = defineProps({
  modelValue: {
   type: [String, Array],
    default: '',
    
  }
})
//声明时间信息
const emits = defineEmits()
//保存图片内存中的临时地址
const imageUrl = ref("")
watch(() => props.modelValue, (val) => {
  if (val) imageUrl.value = val
})
//图片上传成功后

//上传进度值  进度条
const percentage = ref(0)

//上传组件的进度回调函数
const handleProgress = (evt) => {
 percentage.value = Math.floor(evt.percent)
}
// 是否显示进度条
const isShowProgress = ref(false)

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  console.log('上传成功返回：', response)
  imageUrl.value = response.data.name // 用data.name作为图片地址
  emits('update:modelValue', response.data.name)
}
//图片上传前 检查
const beforeAvatarUpload = (rawFile) => {
  isShowProgress.value = true
  // 允许 jpeg 和 svg
  if (!['image/jpeg', 'image/svg+xml'].includes(rawFile.type)) {
    ElMessage.error('图片格式仅支持 JPG 或 SVG!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
</script>

<template>
  <el-progress v-show="isShowProgress" type="circle" :percentage="percentage" width="178"/>
      <el-upload
    v-show="!isShowProgress"
    class="avatar-uploader"
    action="/boss/course/upload"
    method="post"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :on-progress="handleProgress"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" @load="isShowProgress = false"/>
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}


</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>